package com.tom.spring.formework.aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author : tom
 * @project: tom-spring
 * @date : 2018/9/25 16:43
 */
public class AopProxy implements InvocationHandler {
    //默认是jdk代理
    private AopConfig config;
    private Object target;

    public void setConfig(AopConfig config) {
        this.config = config;
    }

    public Object getProxy(Object instance) {
        this.target = instance;
        Class<?> clazz = instance.getClass();
        return Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Method m = this.target.getClass().getMethod(method.getName(),method.getParameterTypes());
        //在原始方法调用以前要执行增强的代码
        if (config.contains(m)) {
            AopConfig.Aspect aspect = config.get(m);
            aspect.getPoints()[0].invoke(aspect.getAspect());
        }

        //反射调用原始的方法
        Object obj = method.invoke(this.target, args);
        System.out.println(args);


        //在原始方法调用以后要执行增强的代码
        if (config.contains(m)) {
            AopConfig.Aspect aspect = config.get(m);
            aspect.getPoints()[1].invoke(aspect.getAspect());
        }
        return obj;
    }
}
